package main

import (
	"fmt"
	"time"
)

/**
 * @description 
 * @time 2019/2/18 23:03
 * @version 
 */

func worker(i int, c chan int) {
	for n := range c{
		//n , ok := <-c
		////判断channel是否有值可以接收
		//if !ok {
		//	break
		//}
		fmt.Printf("Worker %d received %d \n", i, n)
	}
}

func createWorker(i int) chan<- int {
	c := make(chan int)
	go worker(i, c)
	return c
}

func chanDemo() {
	//var c chan int // nil
	var Channels [10] chan<- int
	for i := 0; i < 10; i++ {
		Channels[i] = createWorker(i)
	}

	for i := 0; i < 10; i++ {
		Channels[i] <- 'a' + i
	}

	for i := 0; i < 10; i++ {
		Channels[i] <- 'A' + i
	}
	time.Sleep(time.Microsecond)
}

/**
	缓冲区,提升性能
 */
func bufferedChannel() {
	c := make(chan int, 3)
	go worker(1, c)
	c <- 'a'
	c <- 'b'
	c <- 'c'
	c <- 'd'
	time.Sleep(time.Microsecond)
}

func channelClose() {
	c := make(chan int)
	go worker(1, c)
	c <- 'a'
	c <- 'b'
	c <- 'c'
	c <- 'd'
	close(c)
	time.Sleep(time.Microsecond)
}

func main() {
	chanDemo()
	//bufferedChannel()
	//channelClose()
}
